$(function(){
    "use strict";
    $.ajax({
        url:'/Admin/Admin/addAdmin',
        type:'get',
        success:function(data){
            if(data.code==1){
                let datas = data.data

                let add_groupHtmls = '<option></option>'
                for(let gro = 0; gro < datas.length; gro++){
                    add_groupHtmls += ` <option value="${datas[gro].id}">${datas[gro].role_name}</option> `
                }
                $('#add_group').html(add_groupHtmls)
                $('#edit_group').html(add_groupHtmls)

                let changeHTML = ''
                for( let cha = 0; cha < datas.length; cha++){
                    changeHTML +=  `
                        <li class="change_departmentList_list" data-value="${datas[cha].id}">
                            <i class="iconfont icon-Raidobox"></i>
                            <span>${datas[cha].role_name}</span>
                        </li>
                    `
                }
                changeHTML += `
                    <li class="change_btn_list">
                        <button class="btn btn-sm btn-success confirm">确认调换</button>
                        <button class="btn btn-sm btn-success cancel_btn">取消</button>
                    </li>
                `
                $('.change_List').html(changeHTML)
            }
        }
    })
    $.ajax({
        url:'/Admin/Project/projectNI',
        type:'get',
        success:function(data){
            if(data.code==1){
                let datas = data.res
                let add_projectHtmls = '<option></option>'
                for(let pro = 0; pro < datas.length; pro++){
                    add_projectHtmls += ` <option value="${datas[pro].id}">${datas[pro].pro_name}</option> `
                }
                $('#add_project').html(add_projectHtmls)
                $('#edit_project').html(add_projectHtmls)
            }
        }
    })

    let add_projectList = []
    let add_projectName_List = []
    let edit_projectList = []
    let edit_projectName_List = []

    //全选的功能
    $('#checkAll').on('click',function(){
        var checkboxs =$('input[type=checkbox]:not("#checkAll")');
        for(var i=0;i<checkboxs.length;i++){
            var checkbox=checkboxs[i];
            checkbox.checked=this.checked;
        }
    })
    $('#table_table').on('click','input[type=checkbox]:not("#checkAll")',function(){
        "use strict";
        var isCheckedAll = true;
        var checkboxs =$('input[type=checkbox]:not("#checkAll")');
        for (var i = 0; i < checkboxs.length; i++) {
            if (!checkboxs[i].checked) {
                isCheckedAll = false;
                break;
            }
        }
        $('#checkAll')[0].checked = isCheckedAll;
    })

    // 当添加/调换分组按钮点击时，弹框框显示出来
    $('.operation_btn>a').click(function(e){
        e.preventDefault()
        let showBox = $(this).attr('href')
        if( $(this).html() == '添加' ){
            $(showBox).addClass('active')
        }
        if( $(this).html() == '批量调换分组' ){
            var checkboxs =$('input[type=checkbox]:not("#checkAll")');
            var len = 0;
            for (var i = 0; i < checkboxs.length; i++) {
                if (checkboxs[i].checked) {
                    continue
                }else{
                    len++
                }
            }
            if(len == checkboxs.length){
                $('#yz_modal').html('您还没有选择人员！')
                $('#yz_modal').addClass('active')
                tipShow()
                return
            }
            $(showBox).addClass('active')
        }


    })

    // 当选择所有项目或者部分项目
    $('#add').find('[add_name=add_projectType]').on('change',function(){
        let add_projectType = $('#add').find('[add_name=add_projectType]').val()
        if( add_projectType == '部分项目' ){
            $('#add>li:nth-child(5)').addClass('active')
        }else{
            $('#add>li:nth-child(5)').removeClass('active')
        }
    })
    // 当选择所有项目或者部分项目
    $('#edit').find('[add_name=edit_projectType]').on('change',function(){
        let edit_projectType = $('#edit').find('[add_name=edit_projectType]').val()
        if( edit_projectType == '部分项目' ){
            $('#edit>li:nth-child(5)').addClass('active')
        }else{
            $('#edit>li:nth-child(5)').removeClass('active')
        }
    })
    //当选择项目时
    $('#add_project').on('change',function(){
        let Choose_project_id = $(this).val()
        let Choose_project_name = $('#add_project option:selected').text()
        if(Choose_project_id != '' && Choose_project_name != ''){
            if(add_projectList.length>0){
                let a = 0
                for(let i = 0;i<add_projectList.length;i++){
                    if(add_projectList[i] == Choose_project_id){
                        continue;
                    }else{
                        a++
                    }
                }
                if(a==add_projectList.length){
                    let HTML = $(this).siblings('.project_list').html();
                    HTML += `
                    <li data-value="${Choose_project_id}">
                        <span>${Choose_project_name}</span>
                        <i class="iconfont icon-cha"></i>
                    </li>
                 `
                    $(this).siblings('.project_list').html(HTML);
                    add_projectList.push(Choose_project_id)
                    add_projectName_List.push(Choose_project_name)
                }
            }else{
                let HTML = $(this).siblings('.project_list').html();
                HTML += `
                    <li data-value="${Choose_project_id}">
                        <span>${Choose_project_name}</span>
                        <i class="iconfont icon-cha"></i>
                    </li>
                 `
                $(this).siblings('.project_list').html(HTML);
                add_projectList.push(Choose_project_id)
                add_projectName_List.push(Choose_project_name)
            }
        }
    })
    $('#add').on('click','.project_list i',function(e){
        e.stopPropagation()
        add_projectList.splice($(this).parent().index(),1);
        add_projectName_List.splice($(this).parent().index(),1);
        $(this).parent().remove()
    })

    // 当确认添加的时候
    $('#add_btn').click(function(e){
        e.preventDefault()
        let add_name = $(this).closest('[lll]').find('[add_name=add_name]').val()
        let add_phone = $(this).closest('[lll]').find('[add_name=add_phone]').val()
        let add_group = $(this).closest('[lll]').find('[add_name=add_group]').val()
        let add_group_name = $(this).closest('[lll]').find('[add_name=add_group] option:selected').text()
        let add_projectType = $(this).closest('[lll]').find('[add_name=add_projectType]').val()

        let add_project
        if(!add_name || !add_phone || !add_group){
            $('#yz_modal').html('您内容还没有填完哦！')
            $('#yz_modal').addClass('active')
            tipShow()
            return
        }else{
            if( add_projectType == '所有项目' ){
                add_project= ''
            }else{
                add_project= add_projectList
                if( add_project.length == 0 ){
                    $('#yz_modal').html('您内容还没有填完哦！')
                    $('#yz_modal').addClass('active')
                    tipShow()
                    return
                }
            }
        }
        //防止重复点击按钮
            if( $(this).attr('lock') ) return
            $(this).attr('lock','lock')

        let that = this
        $.ajax({
            url:'/Admin/Admin/addAdmin',
            type:'post',
            data:{
                name:add_name,
                phone:add_phone,
                role_id:add_group,
                pro_ids:add_project
            },
            success:function(data){
                // console.log(data)
                if( data.code==1 ){
                    // let html = $('#table_table').children('tbody').html()
                    let html = `
                        <tr data-index="${data.id}">
                            <td><input type="checkbox" class="checkboxStyle"></td>
                            <td>${add_name}</td>
                            <td>${add_phone}</td>
                            <td>${add_group_name}</td>
                    `
                    if(add_projectType == '所有项目'){
                        html += `<td>${add_projectType}</td>`
                    }else{
                        html += `<td>${add_projectName_List}</td>`
                    }
                    html += `
                            <td class="table_operation_list"><a href="#edit" class="edit">编辑</a><a href="#delete" class="delete">删除</a></td>
                        </tr>
                    `

                    $('#table_table').children('tbody').prepend(html)

                    $(that).closest('[lll]').find('[add_name]').val('')
                    $(that).closest('[lll]').removeClass('active')
                    
                }else{
                    $('#yz_modal').html(data.msg)
                    $('#yz_modal').addClass('active')
                    tipShow()
                    // return
                }
                $(that).removeAttr('lock')
            }
        })

    })

    //当编辑按钮点击时
    $('#table_table').on('click','.edit',function(e){
        let edit_id = $(this).closest('tr').attr('data-index')
        let edit_box = $(this).attr('href')
        $.ajax({
            url:'/Admin/Admin/editAdmin',
            type:'get',
            data:{
                id:edit_id
            },
            success:function(data){
                if(data.code==1){
                    let datas = data.data
                    $('#edit').find('[add_name=edit_name]').val(datas.name)
                    $('#edit').find('[add_name=edit_phone]').val(datas.phone)
                    $('#edit').find('[add_name=edit_group]').val(datas.role_id)
                    if(datas.pro_ids.length == 0){
                        $('#edit').find('[add_name=edit_projectType]').val('所有项目')
                        $('#edit>li:nth-child(5)').removeClass('active')
                    }else{
                        $('#edit').find('[add_name=edit_projectType]').val('部分项目')
                        $('#edit>li:nth-child(5)').addClass('active')
                    }
                    let pro_ids = datas.pro_ids
                    let edit_project = $('#edit_project').children()
                    let edit_project_list_html = ''
                    for(let proi = 0 ; proi < pro_ids.length; proi++){
                        for(let proj = 0 ; proj < edit_project.length; proj++){
                            if(edit_project[proj].value == pro_ids[proi]){
                                edit_project_list_html += `
                                    <li data-value="${pro_ids[proi]}">
                                        <span>${$(edit_project[proj]).text()}</span>
                                        <i class="iconfont icon-cha"></i>
                                    </li>
                                `
                                edit_projectName_List.push($(edit_project[proj]).text())
                            }
                        }
                    }
                    $('#edit').find('.project_list').html(edit_project_list_html)

                    edit_projectList = pro_ids
                    window.sessionStorage['edit_id'] = edit_id
                    $(edit_box).addClass('active')
                }
            }
        })
    })

    //当修改项目时
    $('#edit_project').on('change',function(){
        let Choose_project_id = $(this).val()
        let Choose_project_name = $('#edit_project option:selected').text()
        if(Choose_project_id != '' && Choose_project_name != ''){
            if(edit_projectList.length>0){
                let a = 0
                for(let i = 0;i<edit_projectList.length;i++){
                    if(edit_projectList[i] == Choose_project_id){
                        continue;
                    }else{
                        a++
                    }
                }
                if(a==edit_projectList.length){
                    let HTML = $(this).siblings('.project_list').html();
                    HTML += `
                    <li data-value="${Choose_project_id}">
                        <span>${Choose_project_name}</span>
                        <i class="iconfont icon-cha"></i>
                    </li>
                 `
                    $(this).siblings('.project_list').html(HTML);
                    edit_projectList.push(Choose_project_id)
                    edit_projectName_List.push(Choose_project_name)
                }
            }else{
                let HTML = $(this).siblings('.project_list').html();
                HTML += `
                    <li data-value="${Choose_project_id}">
                        <span>${Choose_project_name}</span>
                        <i class="iconfont icon-cha"></i>
                    </li>
                 `
                $(this).siblings('.project_list').html(HTML);
                edit_projectList.push(Choose_project_id)
                edit_projectName_List.push(Choose_project_name)
            }
        }
    })
    $('#edit').on('click','.project_list i',function(e){
        e.stopPropagation()
        edit_projectList.splice($(this).parent().index(),1);
        edit_projectName_List.splice($(this).parent().index(),1);
        $(this).parent().remove()
    })
    //当保存修改时
    $('#save_btn').click(function(e){
        e.preventDefault()
        // console.log(edit_projectList)
        // console.log(edit_projectName_List)
        e.preventDefault()
        let edit_name = $(this).closest('[lll]').find('[add_name=edit_name]').val()
        let edit_phone = $(this).closest('[lll]').find('[add_name=edit_phone]').val()
        let edit_group = $(this).closest('[lll]').find('[add_name=edit_group]').val()
        let edit_group_name = $(this).closest('[lll]').find('[add_name=edit_group] option:selected').text()
        let edit_projectType = $(this).closest('[lll]').find('[add_name=edit_projectType]').val()

        let edit_project
        if(!edit_name || !edit_phone || !edit_group){
            console.log(1111)
            $('#yz_modal').html('您内容还没有填完哦！')
            $('#yz_modal').addClass('active')
            tipShow()
            return
        }else{
            if( edit_projectType == '所有项目' ){
                edit_project= ''
            }else{
                edit_project= edit_projectList
                if( edit_project.length == 0 ){
                    console.log(222)
                    $('#yz_modal').html('您内容还没有填完哦！')
                    $('#yz_modal').addClass('active')
                    tipShow()
                    return
                }
            }
        }
        //防止重复点击按钮
            if( $(this).attr('lock') ) return
            $(this).attr('lock','lock')

        let that = this
        let edit_id = window.sessionStorage['edit_id']
        $.ajax({
            url:'/Admin/Admin/editAdmin',
            type:'post',
            data:{
                id: edit_id,
                name: edit_name,
                phone: edit_phone,
                role_id: edit_group,
                pro_ids: edit_project
            },
            success:function(data){
                if( data.code==1 ){
                    let html = ''
                    let edit_html = $('#table_table').children('tbody').children(`tr[data-index=${edit_id}]`)
                    html += `
                        
                            <td><input type="checkbox" class="checkboxStyle"></td>
                            <td>${edit_name}</td>
                            <td>${edit_phone}</td>
                            <td>${edit_group_name}</td>
                    `
                    if(edit_projectType == '所有项目'){
                        html += `<td>${edit_projectType}</td>`
                    }else{
                        html += `<td>${edit_projectName_List}</td>`
                    }
                    html += `
                            <td class="table_operation_list"><a href="#edit" class="edit">编辑</a><a href="#delete" class="delete">删除</a></td>
                    `

                    edit_html.html(html)

                    $(that).closest('[lll]').find('[add_name]').val('')
                    $(that).closest('[lll]').removeClass('active')
                }
                $(that).removeAttr('lock')
            }
        })
    })

    //当点击删除的时候
    $('#table_table').on('click','.delete',function(e){
        e.preventDefault()
        let delete_id = $(this).closest('tr').attr('data-index')
        let that = this
        $.ajax({
            url:'/Admin/Admin/delAdmin',
            type:'post',
            data:{
                id:delete_id
            },
            success:function(data){
                if(data.code==1){
                    $('#yz_modal').html(data.msg)
                    $('#yz_modal').addClass('active')
                    tipShow()
                    $(that).parent().parent().remove()
                }else{
                    $('#yz_modal').html(data.msg)
                    $('#yz_modal').addClass('active')
                    tipShow()
                    return
                }
            }
        })

    })

    // 批量修改分组
    $('#change').on('click','.confirm',function(e){
        "use strict";
        e.preventDefault();
        e.stopPropagation();
        let change_arr = [];
        let checkboxs =$('#table_table input[type=checkbox]:not("#checkAll")');
        for (let i = 0; i < checkboxs.length; i++) {
            if (checkboxs[i].checked) {
                change_arr.push( $(checkboxs[i]).closest('tr[data-index]').attr('data-index') )
            }else{
                continue;
            }
        }
        let change_tomove = $('#change').find('i.icon-Raidobox-selectedRai').parent().attr('data-value')
        $.ajax({
            url:'/Admin/Admin/adjust',
            type:'post',
            data:{
                a_ids: change_arr,
                role_id:change_tomove
            },
            success:function(data){
                if(data.code==1){
                    $('#yz_modal').html(data.msg)
                    $('#yz_modal').addClass('active')
                    tipShow()
                    $('#change').removeClass('active')
                    window.location.href = `/Admin/Admin/index`//强制刷新
                }else{
                    $('#yz_modal').html(data.msg)
                    $('#yz_modal').addClass('active')
                    tipShow()
                    return
                }
                checkBox()
            }
        })
    })
    $('#change').on('click','li',function(e){
        "use strict";
        $(this).children('i').addClass('icon-Raidobox-selectedRai').removeClass('icon-Raidobox')
        $(this).siblings().children('i').removeClass('icon-Raidobox-selectedRai').addClass('icon-Raidobox')
    })
    // 批量修改-取消时
    $('#change').on('click','.cancel_btn',function(e){
        $(this).closest('[lll]').removeClass('active')
    })
    // 当点击取消的时候
    $('.cancel_btn').click(function(e){
        $(this).closest('[lll]').removeClass('active')
    })

    // 弹出来的小框框
    function tipShow(){
        window.tipBox = setTimeout(function(){
            // $('#yz_modal').removeClass('active')
            // $('#yz_modal').addClass('fadeOut')
            $('#yz_modal').removeClass('active')
            clearTimeout(tipBox)
        },2000)
    }
    //关闭所有已选择的框框
    function checkBox(){
        let checkboxs =$('input[type=checkbox]');
        console.log(checkboxs)
        for (let i = 0; i < checkboxs.length; i++) {
            if (!checkboxs[i].checked) {
                continue;
            }else{
                checkboxs[i].checked = false
                $(checkboxs[i]).attr('checked',false)
            }
        }
    }

    //拖动拖动拖动
        let add_box =document.getElementById("add");
        let edit_box =document.getElementById("edit");
        add_box.onmousedown = function(ev){
            if($(ev.toElement).attr('id')=='add'){
                ev =ev ||event;
                let oLeft = add_box.offsetLeft;
                let oTop = add_box.offsetTop;
                let a =ev.clientX-oLeft;
                let b =ev.clientY-oTop;
                add_box.onmousemove =function (ev){
                    ev = ev || event;
                    add_box.style.left =ev.clientX-a+'px';
                    add_box.style.top =ev.clientY-b+'px';
                    $(add_box).css({'cursor':'default'})
                }
            }
            
        }
        edit_box.onmousedown = function(ev){
            if($(ev.toElement).attr('id')=='edit'){
                ev =ev ||event;
                let oLeft = edit_box.offsetLeft;
                let oTop = edit_box.offsetTop;
                let a =ev.clientX-oLeft;
                let b =ev.clientY-oTop;
                edit_box.onmousemove =function (ev){
                    ev = ev || event;
                    edit_box.style.left =ev.clientX-a+'px';
                    edit_box.style.top =ev.clientY-b+'px';
                    $(edit_box).css({'cursor':'default'})
                }
            }
        
        }
        document.onmouseup =function(){
            add_box.onmousemove =function(){
                null;
            }
            edit_box.onmousemove =function(){
                null;
            }
        }

})